<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>08_XHR-Ajax网络请求的封装</title>
</head>
<body>

  <script>

    function creatAjax({
      method = 'GET',
      url = '',
      header = {},
      data = {},
      success = () => {},
      fail = () => {}
    }) {

      const xhr = new XMLHttpRequest()

      xhr.responseType = 'json'

      if (method.toUpperCase() === 'GET') {
        const params = Object.keys(data).map(key => `${key}=${data[key]}`).join('&')
        xhr.open(method, url+'?'+params, true)
        setHeader()
        xhr.send()
      } else {
        xhr.open(method, url)
        setHeader()
        xhr.send(JSON.stringify(data))
      }

      // onload监听数据加载完成
      xhr.onload = function () {
        // http状态码判断请求是否成功
        if (xhr.status >= 200 && xhr.status < 300) {
          success(xhr.response)
        } else {
          fail(xhr.responseText)
        }
      }

      function setHeader() {
        if (JSON.stringify(header) !== '{}') {
          Object.keys(header).forEach(key => {
            xhr.setRequestHeader(key, header[key])
          })
        } else {
          xhr.setRequestHeader("Content-type", "application/json")
        }
      }

      return xhr
    }

    creatAjax({
      url: "http://123.207.32.32:1888/02_param/get",
      method: "GET",
      data: {
        name: "XMLHttpRequest",
        age: 18
      },
      success: function(res) {
        console.log("res:", res)
      },
      failure: function(err) {
        // alert(err.message)
      }
    })


  </script>
  
</body>
</html>